package org.budo.time;

import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;

import org.budo.time.impl.BudoTimeFormat;
import org.budo.time.impl.BudoTimePoint;
import org.budo.time.impl.BudoTimeSpan;
import org.budo.time.impl.DateFormatFactory;

/**
 * @author lmw
 */
public class Time {
    public static final DateFormat yyyy_MM_dd_HH_mm_ss = format("yyyy-MM-dd HH:mm:ss");

    public static TimeSpan span(TimePoint from, TimePoint to) {
        return new BudoTimeSpan(from, to);
    }

    public static TimeSpan span(Long milliSeconds) {
        return new BudoTimeSpan(milliSeconds);
    }

    public static TimeFormat timeFormat(String pattern) {
        return new BudoTimeFormat(pattern);
    }

    public static TimeSpan span(Date from, Date to) {
        return new BudoTimeSpan(from, to);
    }

    /**
     * 返回服务器当前时间, 不同服务器的机器时间可能不同
     */
    public static TimePoint now() {
        return new BudoTimePoint(new Date());
    }

    /**
     * 将Date转为TimePoint
     * 
     * @param date 传入空值时不会报错
     */
    public static TimePoint when(Date date) {
        return new BudoTimePoint(date);
    }

    /**
     * milliSeconds转TimePoint
     */
    public static TimePoint when(Number milliSeconds) {
        if (null == milliSeconds) {
            return new BudoTimePoint(null);
        }

        return new BudoTimePoint(new Date(milliSeconds.longValue()));
    }

    /**
     * 指定时间字符串和解析格式，返回对应时间
     */
    public static TimePoint when(String value, DateFormat dateFormat) {
        if (null == value) {
            return new BudoTimePoint(null);
        }

        try {
            synchronized (dateFormat) {
                Date date = dateFormat.parse(value);
                return new BudoTimePoint(date);
            }
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 指定时间字符串和解析格式，返回对应时间
     */
    public static TimePoint when(String value, TimeFormat timeFormat) {
        Date date = timeFormat.parse(value);
        return new BudoTimePoint(date);
    }

    /**
     * 返回时间解析格式
     */
    public static DateFormat format(String format) {
        DateFormatFactory dateFormatFactory = DateFormatFactory.getCurrent();
        return dateFormatFactory.getDateFormat(format);
    }
}